package org.spring.springboot.controller;


        import org.json.JSONArray;
        import org.spring.springboot.domain.Pattern;
        import org.spring.springboot.service.IPatternService;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.*;

        import java.util.HashMap;
        import java.util.List;
        import java.util.Map;
        import org.json.JSONObject;


@RestController
@RequestMapping("/pattern") // 这里定义了总的路径 "/api"
public class PatternController {

    @Autowired
    private IPatternService svc;

    @PostMapping("/getData")
    public Object getfiledata(@RequestBody Map<String, Object> jsonMap) {
        String name = (String) jsonMap.get("name");
        Pattern pat = svc.selectOne(name);
        return pat.toJson();
    }


    @PostMapping("/getAll")
    public List<Object> getAll(@RequestBody Map<String, Object> jsonMap) {
        JSONObject jsonObject = new JSONObject(jsonMap);
        String userid = jsonObject.getString("userid");

        List<Pattern> list= svc.selectAll(userid);

        JSONArray arr = new JSONArray();
        for (Pattern p:list) {
            JSONObject obj = p.toJson();
            arr.put(obj);
        }
        return arr.toList();
    }

    @PostMapping("/save")
    public Map<String, Object> save(@RequestBody Map<String, Object> jsonMap) {
        JSONObject jsonObject = new JSONObject(jsonMap);
        Pattern obj = new Pattern();
        obj.setName(jsonObject.getString("name"));
        obj.setLinedefs(jsonObject.getString("linedefs"));
        obj.setDescription(jsonObject.getString("description"));
        obj.setIndex(jsonObject.getInt("index"));
        svc.save(obj);
        JSONObject retJson = new JSONObject();
        retJson.put("ret",true);
        return retJson.toMap();
    }


    @PostMapping("/delete")
    public Map<String, Object> delete(@RequestBody Map<String, Object> jsonMap) {
        JSONObject jsonObject = new JSONObject(jsonMap);
        String uuid = jsonObject.getString("uuid");
        String name = jsonObject.getString("name");
        svc.delete(name);
        JSONObject retJson = new JSONObject();
        retJson.put("ret",true);
        return retJson.toMap();
    }
}
